<!-- src/components/common/Tab.vue -->
<template>
  <div class="tab-wrapper">
    <!-- 标题栏 -->
    <div class="tab-header">
      <div v-for="(item, index) in items" :key="index" class="tab-title" :class="{ active: activeIndex === index }"
        @click="handleTabClick(index)">
        {{ item.title }}
      </div>
    </div>

    <!-- 内容区 -->
    <div class="tab-content">
      <!-- 渲染当前激活项的内容 -->
      <component :is="items[activeIndex]?.content" v-if="items[activeIndex]" />
    </div>
  </div>
</template>

<script setup>
import { ref, onMounted, useSlots, h, watch, nextTick, computed } from 'vue'
import TabItem from './TabItem.vue'
//  声明要 emit 的事件（推荐写法，用于类型提示和文档）
const emit = defineEmits(['change'])

const activeIndex = ref(0)
const items = ref([])
const slots = useSlots()

// 监听 activeIndex 变化，触发 change 事件
watch(activeIndex, (newIndex) => {
  emit('change', newIndex)
  // 将当前激活索引保存到sessionStorage
  sessionStorage.setItem('tabActiveIndex', newIndex.toString())
})

// 监听插槽变化，更新 items
watch(() => slots.default?.(), () => {
  updateItems()
}, { deep: true })

// 更新 items 的函数
const updateItems = async () => {
  const children = slots.default?.() || []
  await nextTick()
  // 过滤并提取 TabItem 的 title 和内容（VNode）
  items.value = children
    .filter(vnode => vnode.type === TabItem)
    .map(vnode => ({
      title: vnode.props?.title || '标签',
      content: () => h(vnode.type, vnode.props, vnode.children)
    }))
  
  // 从sessionStorage恢复激活索引
  const savedIndex = sessionStorage.getItem('tabActiveIndex')
  if (savedIndex !== null) {
    const index = parseInt(savedIndex, 10)
    if (index >= 0 && index < items.value.length) {
      activeIndex.value = index
    }
  }
}

// 添加点击处理函数，防止重新渲染时重置索引
const handleTabClick = (index) => {
  activeIndex.value = index
}

onMounted(async () => {
  await updateItems()
})
</script>

<style scoped>
/* 你的样式保持不变 */
.tab-wrapper {
  width: 100%;
}

.tab-header {
  display: flex;
  background-color: #161622;
  padding: 0 10px;
}

.tab-title {
  flex: 1;
  text-align: center;
  padding: 12px 0;
  color: #aaa;
  font-size: 14px;
  cursor: pointer;
  position: relative;
}

.tab-title.active {
  color: #fff;
  font-weight: bold;
}

.tab-title.active::after {
  content: '';
  position: absolute;
  bottom: 0;
  left: 50%;
  transform: translateX(-50%);
  width: 30px;
  height: 2px;
  background-color: #409eff;
}

.tab-content {
  padding: 15px 0;
}
</style>